<template>
    <div id='wrap'>
        <h1>侦听器watch</h1>
        <!-- 单值侦听 -->
        <button @click="count++">自增：{{ count }}</button>
        <hr>
        <!-- 多值侦听 -->
        <button @click="add">自增：{{ `${x},${y}` }}</button>
        <hr>
        <!-- 侦听返回值 -->
        <button @click="sum">增加：{{ sum() }}</button>
        <button @click="name = 'Matsuyuki'"></button>
        <hr>
        <!-- 深度侦听 -->
        <button @click="user1.details.age++">点击改变{{ user1.details.age }}</button>
        <hr>
        <!-- 立即执行一次侦听 -->
        <button @click="message = '你好'">点击改变{{ message }}</button>
    </div>
</template>
<script lang='ts'>
export default {
    name: 'watch',
}
</script>
<script lang='ts' setup>
import { watch, ref, h, type Ref, isRef, reactive, isReactive, readonly, isReadonly, toRef, toRefs, unref, isProxy } from 'vue';
// 单值侦听
const count = ref(0);
watch(count, (newValue, oldValue) => {
    console.log(`count响应式变量改变从${oldValue}到${newValue}`);
});

// 多值侦听
const x = ref(0);
const y = ref(0);
const add = () => {
    x.value++;
    y.value++;
}
watch([x, y], ([newX, newY], [oldX, oldY]) => {
    console.log(`x响应式变量改变从${oldX}到${newX},y响应式变量改变从${oldY}到${newY}`);
})

//帧听返回值
const sum = () => {
    const suns = x.value + y.value;
    return suns;
}
watch(sum, (newValue, oldValue) => {
    console.log(`sum响应式变量改变从${oldValue}到${newValue}`);
})
const name = ref('Syaro')
watch(() => name.value.length, (newLength, oldLength) => {
    console.log(`name响应式变量改变从${oldLength}到${newLength}`);
});

//深度侦听对象：侦听对象的子属性变化需要用deep：true
const user1 = reactive({
    name: 'Syaro',
    details: {
        age: 18,
        hobbies: ['reading', 'cooking']
    }
})
watch(user1, (newValue, oldValue) => {
    console.log(`user1响应式变量${user1.details.age}`);
}, { deep: true })

//垃圾执行：绑定后立即触发一次侦听器，用immediate: true
const message = ref('hello');
watch(message, (oldValue, newValue) => {
    console.log(`message响应式变量改变从${oldValue}到${newValue}`);
}, { immediate: true })
</script>
<style lang='scss'>
@use '@/assets/common.scss';
</style>